import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { exec, ExecException, ExecOptions } from 'child_process';
const zipper = require("zip-local");

export class OSUtils{

	public static CopyFile(fromPath:string|undefined,toPath:string):void{
		if(fromPath == undefined){
			return;
		}
		fs.writeFileSync(toPath,fs.readFileSync(fromPath));
	}

	public static SaveStringToFile(filePath:string,strContent:string):void{
		fs.writeFileSync(filePath,strContent);
	}

	public static GetFileMD5(filePath:string,callBack:Function):void{
		let start:number = new Date().getTime();
		
		let md5sum:crypto.Hash = crypto.createHash('md5');
		let stream:fs.ReadStream = fs.createReadStream(filePath);
		stream.on('data', function(chunk) {
			md5sum.update(chunk);
		});

		stream.on('end', function() {
			let str = md5sum.digest('hex').toLowerCase();
			// console.log('文件:'+filePath+',MD5签名为:'+str+'.耗时:'+(new Date().getTime()-start)/1000.00+"秒");
			callBack(str);
		});
	}

	public static execCmd(cmd:string,options:ExecOptions,callBack:Function){
		exec(cmd,options, function(err:ExecException | null,stdout:string,stderr:string){
			if(err) {
				console.log('child process err:' + stderr);
				console.log(stdout);
			} else {
				console.log(stdout);
			}
			if(typeof callBack == 'function'){
				callBack(err,stdout,stderr);
			}
		});
	}
	

    public static DelDir(strPath:string):void{
        let arr:string[]=fs.readdirSync(strPath);

        for(let i:number =0;i < arr.length;i++){
			let strItem:string = path.join(strPath , arr[i]);
            //读取文件信息，以便于判断是否是一个文件或目录
            let stats:fs.Stats=fs.statSync(strItem);
    
            if(stats.isFile()){
                //判断为真，是文件则执行删除文件
                fs.unlinkSync(strItem);
            }else if(stats.isDirectory()){
                //判断为文件夹，就调用自己，递归的入口
                OSUtils.DelDir(strItem);
            }
        }
        //删除空目录
        fs.rmdirSync(strPath);
    }

	public static DelFile(strPath:string){
		fs.unlinkSync(strPath);
	}

	public static Zip(strPath:string,zipFileName:string){
		console.log("开始压缩:"+zipFileName);
		zipper.sync.zip(strPath).compress().save(zipFileName);
		console.log("压缩结束:"+zipFileName);
	}

}